﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using System.Collections;
using System.Globalization;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.UserCode;
using ILX.Portal.DAL;
namespace DemoConsoleApp
{
    class Program
    {
        
      //  static string xmlData = "<Method ID=\"1\"><SetList>125ee8e9-48fc-4ed3-8f04-951e4acff482</SetList><SetVar Name=\"ID\">New</SetVar><SetVar Name=\"Cmd\">Save</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#WFItemID\">14</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#SourceListTitle\">test1</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#ListUrl\">/Lists/test1</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#Title\">2-Create Change Initiate LCN : Marketing Approval</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#ApprovalLevel\">2</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#On_x0020_Rework_x0020_Go_x0020_Back_x0020_To\">1</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#Approvers\">15;#Test1;#16;#Test Two</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#Form_x0020_Type\">Approval</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#AllowReSubmitInput\"></SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#Project\">rf</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#DueDate\">2012-09-04T23:59:57Z</SetVar></Method>";
        static string xmlData = "<Method ID=\"1\"><SetList>125ee8e9-48fc-4ed3-8f04-951e4acff482</SetList><SetVar Name=\"urn:schemas-microsoft-com:office:office#On_x0020_Rework_x0020_Go_x0020_Back_x0020_To\">1</SetVar><SetVar Name=\"ID\">New</SetVar><SetVar Name=\"Cmd\">Save</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#WFItemID\">14</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#SourceListTitle\">test1</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#ListUrl\">/Lists/test1</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#Title\">2-Create Change Initiate LCN : Marketing Approval</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#Approvers\">15;#Test1;#16;#Test Two</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#AllowReSubmitInput\"></SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#Project\">rf</SetVar><SetVar Name=\"urn:schemas-microsoft-com:office:office#DueDate\">2012-09-04T23:59:57Z</SetVar></Method>";

        private static void batchInsert()
        {
            string curName="";
            using (SPSite site = new SPSite("http://spdev"))
            {
                using (SPWeb objWeb = site.OpenWeb())
                {
                    var sa = objWeb.AllUsers["sp\\test1"];
                   curName = sa.ToString();
                }
            }

            TaskActivityManager mgr = new TaskActivityManager("http://spdev");
            TaskActivityMaster entity = new TaskActivityMaster();
            entity.Title = "test1";
           // entity.Id = 1;
            entity.ApprovalLevel = 1;
            entity.ApprovalType = ApprovalType.Serial;
            entity.OnReworkGoBackTo = 0;
            entity.TaskActivityId = 1;
            entity.ApproversId.Add(15);
            entity.ApproversId.Add(16);
            entity.ApproversId.Add(10);
           // entity.ApproversImnName.Add(curName);
            entity.DueDays = 2;
           // entity.TaskActivityTitle = "";
           // mgr.Create(entity);
           
           // var data = mgr.Read(5);

           // string aa = "aaa";
           // return;


            using (SPSite site = new SPSite("http://spdev"))
            {
                using (SPWeb objWeb = site.OpenWeb())
                {

                    while (objWeb.Lists["ApprovalLevelCustom"].Items.Count > 0)
                    {
                        objWeb.Lists["ApprovalLevelCustom"].Items.Delete(0);
                    }

                    //string output = objWeb.ProcessBatchData(string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ows:Batch OnError=\"Return\">{0}</ows:Batch>", xmlData) );

                    //Console.WriteLine(output);
                }
            }
        }


        private static void Approveask(int itemid)
        {
            int wfItemID = default(int);
            Guid wfListID = Guid.Empty;
            string wfName = string.Empty;
            SPUserToken userToken = null;
            using (SPSite site = new SPSite("http://spdev"))
            {
                using (SPWeb objWeb = site.OpenWeb())
                {
                    //SPUserToken curUserToken  = SPContext.Current.Web.Users[""].UserToken;
                    userToken = objWeb.Site.RootWeb.AllUsers["sp\\test1"].UserToken;
                    //objWeb.Users.g
                    SPList list = objWeb.Lists["TaskHandler"];
                    SPList listTasks = objWeb.Lists["ILXWFTask"];


                    SPListItem item = listTasks.GetItemById(itemid);
                    //wfItemID =
                    int.TryParse(string.Format("{0}", item["WorkflowItemId"]), out wfItemID);
                    wfName = item["WorkflowName"].ToString();
                    if (item["WorkflowListId"] != null)
                    {
                        wfListID = new Guid(string.Format("{0}", item["WorkflowListId"]));
                    }
                }
            }

            Approveask(wfItemID, wfListID, wfName, itemid, userToken);

        }


        private static void Approveask(int wfItemID, Guid wfListID, string wfName, int taskID, SPUserToken curUserToken)
        {
            using (SPSite site = new SPSite("http://spdev", curUserToken))
            {
                using (SPWeb objWeb = site.OpenWeb())
                {
                    //SPUserToken curUserToken  = SPContext.Current.Web.Users[""].UserToken;

                    SPList list = objWeb.Lists[wfListID];

                    SPListItem item = list.GetItemById(wfItemID);

                    //SPWorkflowTemplate template = objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);

                    Console.WriteLine(item.Title);

                    SPWorkflowTaskCollection tskC = (from SPWorkflow spwfa in item.Workflows
                                                     where spwfa.AssociationId ==
                                                     (
                                                         (
                                                          from SPWorkflowAssociation associ in list.WorkflowAssociations
                                                          where associ.Name.Equals("mul", StringComparison.CurrentCultureIgnoreCase)
                                                          select associ.Id
                                                          )
                                                       .
                                                       FirstOrDefault()
                                                       )
                                                     select spwfa.Tasks
                               ).FirstOrDefault();


                    var de = from SPWorkflowTask sss in tskC
                             where string.Format("{0}",
                                 sss["Status"]) != "Completed" && sss.ID == taskID
                             select sss;
                   
                    foreach (var tsk in de)
                    {

                            Console.WriteLine(list.WorkflowAssociations[0].Id);
                            Console.WriteLine(tsk.Name);
                            Console.WriteLine(tsk.ID);
                            Console.WriteLine(tsk.Title);
                            // alter the task
                            Hashtable ht = new Hashtable();
                            ht[SPBuiltInFieldId.Completed] = "TRUE";
                            ht[SPBuiltInFieldId.PercentComplete] = 1;
                            ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);
                            Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
              
                    }

                    //item.Workflows[0].Tasks[0].
                   // Console.WriteLine("***********************************");
                    objWeb.Update();

                }
            }
        }



        private static void Approveask1(int itemid)
        {
            using (SPSite site = new SPSite("http://spdev"))
            {
                using (SPWeb objWeb = site.OpenWeb())
                {
                    //SPUserToken curUserToken  = SPContext.Current.Web.Users["sp\\test1"].UserToken;
                    using (SPSite site1 = new SPSite("http://spdev"))
                    {
                        using (SPWeb objWeb1 = site1.OpenWeb())
                        {
                        }
                    }

                    SPList list = objWeb.Lists["TaskHandler"];
                    SPList listTasks = objWeb.Lists["ILXWFTask"];


                    SPListItem item = list.GetItemById(itemid);
                    //SPWorkflowTemplate template =          objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);
                    Console.WriteLine(item.Title);
                    SPWorkflowTaskCollection tskC =  (from SPWorkflow spwfa in item.Workflows
                                where spwfa.AssociationId ==
                                (
                                    (
                                     from SPWorkflowAssociation associ in list.WorkflowAssociations
                                     where associ.Name.Equals("mul", StringComparison.CurrentCultureIgnoreCase)
                                     select associ.Id
                                     )
                                  .
                                  FirstOrDefault()
                                  )
                                select spwfa.Tasks
                               ).FirstOrDefault()
                               
                               ;


                  var de = from SPWorkflowTask sss in tskC where string.Format("{0}",
                               sss["Status"]) != "Completed" select sss;

                  foreach (var tsk in de)
                  {
                      //if (string.Format("{0}", tsk["Status"]) != "Completed")
                      {
                          Console.WriteLine(list.WorkflowAssociations[0].Id);
                          Console.WriteLine(tsk.Name);
                          Console.WriteLine(tsk.ID);
                          Console.WriteLine(tsk.Title);
                          // alter the task
                          Hashtable ht = new Hashtable();
                          ht[SPBuiltInFieldId.Completed] = "TRUE";
                          ht[SPBuiltInFieldId.PercentComplete] = 1;
                          ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);

                          // Mark the entry as approved
                         // Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
                      }
                  }
                  Console.WriteLine("***********************************");
                  return;
                    foreach (SPWorkflowTask tsk in tskC)// item.Tasks)
                    {
                        if (string.Format("{0}", tsk["Status"]) != "Completed")
                        {
                            Console.WriteLine(list.WorkflowAssociations[0].Id);
                            Console.WriteLine(tsk.Name);
                            Console.WriteLine(tsk.ID);
                            Console.WriteLine(tsk.Title);
                            // alter the task
                            Hashtable ht = new Hashtable();
                            ht[SPBuiltInFieldId.Completed] = "TRUE";
                            ht[SPBuiltInFieldId.PercentComplete] = 1;
                            ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);

                            // Mark the entry as approved
                            Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
                        }
                    }

                    objWeb.Update();
                }
            }
        }



        static void Main(string[] args)
        {
            batchInsert();
            return;

            var list11 = new List<string> { "a", "b", "a", "c", "a", "b" };
            var q = list11.GroupBy(x => x)
                        .Select(g => new { Value = g.Key, Count = g.Count() })
                        .OrderByDescending(x => x.Count);

            foreach (var x in q)
            {
                Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
            }

            
            return;
            //string data = "1;#Sales;#2;#MMMM";

            //string[] aa = data.Split(';', '#');

         
            //return;
            using (SPSite site = new SPSite("http://devsp:7500"))
            {

                using (SPWeb objWeb = site.OpenWeb())
                {

                    objWeb.AllowUnsafeUpdates = true;

                       Console.WriteLine(SPResource.GetString(
                           new CultureInfo((int)objWeb.Language, false), 
                           "WorkflowTaskStatusTerminate", new object[0]));

                       SPList list_1 = objWeb.Lists["Condidates"];
                       SPListItem itmoo = list_1.Items[0];

                       foreach (SPWorkflowTask tsk in itmoo.Tasks)// item.Tasks)
                       {

                           tsk["AssignedTo"] = objWeb.EnsureUser("devsp\\u4").ID.ToString() + ";#" + "devsp\\u4";
                           IFormatProvider culture = new System.Globalization.CultureInfo("en-GB", true);
                           DateTime dt2 = DateTime.Parse
                               (
                               "01/08/2012",
                               culture,
                               System.Globalization.DateTimeStyles.AssumeLocal
                               );
                           tsk["DueDate"] = dt2;
                           Console.WriteLine(list_1.WorkflowAssociations[0].Id);
                           Console.WriteLine(tsk.Name);
                           Console.WriteLine(tsk.ID);
                           Console.WriteLine(tsk.Title);
                           // alter the task
                           Hashtable ht = new Hashtable();
                           ht[SPBuiltInFieldId.Completed] = "FALSE";
                           ht["DueDate"] = dt2;
                           ht["ApprovalStatus"] = "ReAssigened";

                           ht["DefaultLocal"] = "en-GB";
                           //ht[SPBuiltInFieldId.DueDate] = System.DateTime.Now.AddDays(100);
                           //ht[SPBuiltInFieldId.AssignedTo] = "devsp\\u4";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);

                           // Mark the entry as approved
                           Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
                           break;
                       }


                     
                       //itmoo[SPBuiltInFieldId.AssignedTo] = "devsp\\u4";// objWeb.EnsureUser("devsp\\u4");
                       //itmoo.SystemUpdate(false);
                       return;


                    ////SPList configList = objWeb.Lists["taskapprovalConfig"];
                    ////var listItem = (from SPListItem itm in configList.Items
                    ////                where
                    ////              itm["ApprovalLevel"].ToString() == 1.ToString()
                    ////                &&
                    ////                itm["Project"].ToString().Contains(";#Sales")
                    ////                select itm).
                    ////                FirstOrDefault();
                    ////if (listItem == null)
                    ////{
                    ////  //  this.IsAllTaskCompleted = true;
                    ////}
                    ////return;
                    SPList list = objWeb.Lists["Condidates"];

                    SPListItem itTK = list.GetItemById(306);

                    string strTKs = "";
                    string completed = "";
                    Guid pendingID=default(Guid) ;
                    foreach (SPWorkflowTask itemoo in itTK.Workflows[0].Tasks)
                    {
                        SPListItem ity = ((Microsoft.SharePoint.SPListItem)(itemoo));
                        completed += ity["Completed"].ToString();
                        if (!ity["Completed"].ToString().Equals("true", StringComparison.CurrentCultureIgnoreCase))
                        {
                            strTKs += ity["GUID"].ToString() + ",";
                            pendingID = ity.UniqueId;
                        }


                        Console.WriteLine(ity["GUID"]);
                        Console.WriteLine(ity.UniqueId);
                        for (int i = 1110; i < ity.Fields.Count; i++)
                        {
                            Console.WriteLine("---------------");
                            Console.WriteLine(ity.Fields[i]);
                            
                            Console.WriteLine(  ity[i]);
                        }
                    }


                    SPList listTst = objWeb.Lists["Tasks"];

                    SPListItem itmaa = itTK;// list.Items[0];

                    Console.WriteLine(1111);
                    SPWorkflowTask tskDel = null;
                    foreach (SPWorkflowTask item11 in itTK.Tasks)
                    {
                        Console.WriteLine(string.Format("ID={0}---UniqueID={1}-- Title=", item11.ID, item11.UniqueId, item11.Title));
                        if (item11.UniqueId == pendingID)
                        {
                            tskDel = item11;
                            break;
                            Console.WriteLine(string.Format("ID={0}---UniqueID={1}-- Title=", item11.ID, item11.UniqueId, item11.Title));
                        }
                    }
                   // tskDel["Status"] = "System";
                  // tskDel.Delete();
                    //list.Items[0].Tasks

                    Console.WriteLine(1111);
                    return;

                    SPFieldUserValueCollection users = new SPFieldUserValueCollection();
                    //users.Add( new SPFieldUserValue(

                    SPListItem item = list.Items[0];

                    SPWorkflowTaskCollection tskColl = item.Workflows[0].Tasks;
                    SPWorkflowTask tsls = tskColl[0];
                    tsls[SPBuiltInFieldId.Completed] = "TRUE";
                    tsls[SPBuiltInFieldId.PercentComplete] = 1;
                    tsls[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);

                    tsls.SystemUpdate(false);

                    return;
                    Guid wfBaseId = new Guid("{C7EF10FF-6090-46BE-A396-953761AAD3CA}");
                    Console.WriteLine(item.Title);
                    var tskC = (from SPWorkflow spwfa in item.Workflows
                                where spwfa.AssociationId ==
                                (
                                    (
                                     from SPWorkflowAssociation associ in list.WorkflowAssociations
                                     where associ.Name.Equals("TaskHandler", StringComparison.CurrentCultureIgnoreCase)
                                     select associ.Id
                                     )
                                  .
                                  FirstOrDefault()
                                  )
                                select spwfa
                               ).FirstOrDefault();

                  //  SPWorkflowManager.CancelWorkflow(tskC);
                   return;
                    foreach (SPWorkflowTask tsk in tskC.Tasks)// item.Tasks)
                    {

                        Console.WriteLine(list.WorkflowAssociations[0].Id);
                        Console.WriteLine(tsk.Name);
                        Console.WriteLine(tsk.ID);
                        Console.WriteLine(tsk.Title);
                        // alter the task
                        Hashtable ht = new Hashtable();
                        ht[SPBuiltInFieldId.Completed] = "TRUE";
                        ht[SPBuiltInFieldId.PercentComplete] = 1;
                        ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);

                        // Mark the entry as approved
                        Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
                        break;

                        string a = "11";
                        Console.WriteLine(tsk.Name);
                    }
                    
                   SPWorkflowAssociation associationTemplate = list.WorkflowAssociations.GetAssociationByName("TaskHandler", new CultureInfo(1033));

                  //  site.WorkflowManager.StartWorkflow(item, associationTemplate, "Parallel:devsp\\u1;devsp\\u2;devsp\\u3", true);
                    // site.WorkflowManager.StartWorkflow(item,);
                }
            }

            //SPUtility.WorkflowHelper wfh = new SPUtility.WorkflowHelper();
            

           // string url = "http://devsp:7500";
          //  Console.WriteLine( wfh.ApproveWFProcess(url, "MainList", "Recruitment"));

            return;

            SPUtility.ListActivity act = new SPUtility.ListActivity();
            Dictionary<string,string> dict = new Dictionary<string,string>();
            dict.Add("Title","22222");
          //  act.DeleteItem(url,"MainList",7);

            //SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("MyCategory", TraceSeverity.Medium, EventSeverity.Information), TraceSeverity.Medium, "My log message");

            //SPUtility.LogHandler.LogError(SPUtility.LogType.ApplicationPage, "ApplicationPageaaaaaaaaaaaaaaaaaaaaaaaaa");
            //SPUtility.LogHandler.LogError(SPUtility.LogType.BusinessLayer, "BusinessLayeraaaaaaaaaaaaaaaaaaaaaaaaa");
            //SPUtility.LogHandler.LogError(SPUtility.LogType.CommonUtility, "CommonUtilityaaaaaaaaaaaaaaaaaaaaaaaaa");
            //SPUtility.LogHandler.LogError(SPUtility.LogType.DataLayer, "DataLayeraaaaaaaaaaaaaaaaaaaaaaaaa");
            //SPUtility.LogHandler.LogError(SPUtility.LogType.UserControl, "UserControlaaaaaaaaaaaaaaaaaaaaaaaaa");

            
           // return;
            using (SPSite site = new SPSite("http://devsp:7500"))
            {
                using (SPWeb objWeb = site.OpenWeb())
                {
                    SPList list = objWeb.Lists["Condidates"];
                    SPList listTasks = objWeb.Lists["Tasks"];


                    SPListItem item = list.Items[0];
                    //SPWorkflowTemplate template =          objWeb.WorkflowTemplates.GetTemplateByName("Approval", objWeb.Locale);
                    Console.WriteLine(item.Title);
                    var tskC = (from SPWorkflow spwfa in item.Workflows
                                where spwfa.AssociationId ==
                                (
                                    (
                                     from SPWorkflowAssociation associ in list.WorkflowAssociations
                                     where associ.Name.Equals("mul", StringComparison.CurrentCultureIgnoreCase)
                                     select associ.Id
                                     )
                                  .
                                  FirstOrDefault()
                                  ) 
                               select spwfa.Tasks
                               ).FirstOrDefault();


                    foreach (SPWorkflow aitem in item.Workflows)
                    {
                       // SPWorkflowManager.CancelWorkflow(aitem);
                    }
                    return;

                    foreach (SPWorkflowTask tsk in tskC)// item.Tasks)
                    {

                        Console.WriteLine(list.WorkflowAssociations[0].Id);
                        Console.WriteLine(tsk.Name);
                        Console.WriteLine(tsk.ID);
                        Console.WriteLine(tsk.Title);
                        // alter the task
                        Hashtable ht = new Hashtable();
                        ht[SPBuiltInFieldId.Completed] = "TRUE";
                        ht[SPBuiltInFieldId.PercentComplete] = 1;
                        ht[SPBuiltInFieldId.TaskStatus] = "Completed";//SPResource.GetString(new CultureInfo((int)objWeb.Language, false), "WorkflowTaskStatusComplete", new object[0]);

                        // Mark the entry as approved
                        Console.WriteLine(SPWorkflowTask.AlterTask((tsk as SPListItem), ht, true).ToString());
                       break;
                    }
                    
                    objWeb.Update();
                }
            }



        }


        static void Main22(string[] args)
        {
            string taskFields = @"Title,
                                        ApprovalLevel,
                                        OnReAssignGoBackTo,
                                        Approver,
                                        TaskType,
                                        FormType,
                                        AllowReSubmitInput,
                                        Project,
                                        DueDate";
            string listGuid = "C7F6A36F-BD2E-484A-A18C-05D9F69AC554";
            string workflowName = "Recruitment";
            ProcessBatchInsert(listGuid, workflowName, taskFields, 2, "MainList", "Lists/MainList");
        }

        static double ActualDays(int Days)
        {
            int k = 0;
            double actualDays = 0;
            string weekend1 = "sunday";
            string weekend2 = "saturday";
            while (k < Days)
            {
               
                if (
                    System.DateTime.Now.AddDays((double)k).DayOfWeek.ToString().Equals(weekend1, StringComparison.CurrentCultureIgnoreCase)
                    ||
                    System.DateTime.Now.AddDays((double)k).DayOfWeek.ToString().Equals(weekend2, StringComparison.CurrentCultureIgnoreCase)
                    )
                {
                    actualDays++;
                }
                actualDays++;
                k++;
            }
            if (
                    System.DateTime.Now.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend1, StringComparison.CurrentCultureIgnoreCase)
                    ||
                    System.DateTime.Now.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend2, StringComparison.CurrentCultureIgnoreCase)
                    )
            {
                actualDays = ActualDays((int)actualDays + 1);
            }
            return actualDays;
        }

        static DateTime ActualDate(DateTime curDate , int Days, SPList holidayList)
        {
            int k = 1;
            double actualDays = 1;
            string weekend1 = "sunday";
            string weekend2 = "saturday";
            while (k <= Days)
            {
                if (
                    !curDate.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend1, StringComparison.CurrentCultureIgnoreCase)
                    &&
                    !curDate.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend2, StringComparison.CurrentCultureIgnoreCase)
                    )
                {
                    var dat = (from SPListItem itm in holidayList.Items
                               where itm["HolidayDate"] != null &&
                              String.Format("{0:d}", (DateTime)itm["HolidayDate"]) == String.Format("{0:d}", curDate.AddDays(actualDays))
                               select itm).FirstOrDefault();
                    if (dat == null)
                    {

                        k++;
                    }
                }
               
                actualDays++;
               // k++;
               
            }
            if (Days == 0)
            {


                var dat1 = (from SPListItem itm in holidayList.Items
                            where itm["HolidayDate"] != null &&
                           String.Format("{0:d}", (DateTime)itm["HolidayDate"]) == String.Format("{0:d}", curDate)
                            select itm).FirstOrDefault();
                if (dat1 != null)
                {
                   // curDate = curDate.AddDays(1);
                    return ActualDate(curDate.AddDays(1), 1, holidayList);
                }
            }
            else
            {
                actualDays=(k > 0 ? actualDays - 1 : actualDays);
            }
            if (
                    curDate.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend1, StringComparison.CurrentCultureIgnoreCase)
                    ||
                    curDate.AddDays(actualDays).DayOfWeek.ToString().Equals(weekend2, StringComparison.CurrentCultureIgnoreCase)
                    )
            {
               

                return ActualDate(curDate.AddDays(actualDays +1), 0, holidayList);
                //actualDays++;
            }


            return curDate.AddDays(actualDays);
        }
        static void ProcessBatchInsert(string targetListGuid, string workflowName, string taskFields, int WFItemID, string SourceListTitle, string ListUrl)
        {
            //double aa = ActualDays(5);

            double prevDueDays = 0;
            double hourDiff = (24 - (System.DateTime.Now.Minute + 1) / 60D);
            hourDiff = Math.Round(hourDiff, 2) - System.DateTime.Now.Hour;
           // return;
           // string listGuid = "C7F6A36F-BD2E-484A-A18C-05D9F69AC554";
            StringBuilder query = new StringBuilder();
           
            using (SPSite site = new SPSite("http://devsp:7500"))
            {

                using (SPWeb objWeb = site.OpenWeb())
                {
                    SPList configList = objWeb.Lists["taskapprovalConfig"];
                    SPList holidayList = objWeb.Lists["Holiday"];
                    StringBuilder sbHoliday = new StringBuilder();
                   
                    var listItem = (from SPListItem itm in configList.Items
                                    where
                                    itm["Project"] != null
                                    &&
                                    itm["Project"].ToString().Contains(";#" + workflowName)
                                    select itm);

                    StringBuilder query1 = new StringBuilder();
                    DateTime curDate = System.DateTime.Now;
                    foreach (var item in listItem)
                    {
                        query.AppendFormat(
                       "<Method ID=\"{0}\">" +
                       "<SetList>{1}</SetList>" +
                       "<SetVar Name=\"ID\">New</SetVar>" +
                       "<SetVar Name=\"Cmd\">Save</SetVar>", item.ID, targetListGuid);
                        foreach (string fld in taskFields.Replace("\r", "").Replace("\n", "").Replace(" ", "").Split(','))
                        {
                            query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>", WFItemID, "urn:schemas-microsoft-com:office:office#WFItemID");
                            query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>", SourceListTitle, "urn:schemas-microsoft-com:office:office#SourceListTitle");
                            query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>", ListUrl, "urn:schemas-microsoft-com:office:office#ListUrl");

                            if (fld.Contains("DueDate"))
                            {
                                curDate = ActualDate(curDate, int.Parse(item["TaskDueDays"].ToString()), holidayList);
                                query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>",
                                     Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(
                                    curDate.AddHours(
                                     hourDiff)),
                                     "urn:schemas-microsoft-com:office:office#" + fld);
                            }
                            else
                                query.AppendFormat("<SetVar Name=\"{1}\">{0}</SetVar>", item[fld], "urn:schemas-microsoft-com:office:office#" + fld);
                        }
                        query.AppendFormat("</Method>");
                    }

                    string output = objWeb.ProcessBatchData(string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                           "<ows:Batch OnError=\"Return\">{0}</ows:Batch>", query.ToString()));
                    Console.WriteLine(output);
                }
            }
        }
    }
}
